<template>
  <div class="table-box">
    <ProTable
      ref="proTable"
      :columns="columns"
      :request-api="getTableList"
      :init-param="initParam"
      :data-callback="dataCallback"
      @darg-sort="sortTable"
      row-key="processInstanceId"
    >
      <!-- 表格 header 按钮 -->
      <!-- <template #tableHeader="scope">
        <el-button type="primary" :icon="CirclePlus" @click="addTemplate">新增</el-button>
        <el-button type="primary" plain @click="EditGroup(scope.selectedList)">编辑</el-button>
        <el-button type="danger" :icon="Delete" plain :disabled="!scope.isSelected" @click="batchDelete(scope.selectedList)">
          批量删除
        </el-button>
      </template> -->
      <!-- Expand -->
      <template #expand="scope">
        {{ scope.row }}
      </template>
      <!-- usernameHeader -->
      <template #usernameHeader="scope">
        <el-button type="primary" @click="ElMessage.success('我是通过作用域插槽渲染的表头')">
          {{ scope.column.label }}
        </el-button>
      </template>
      <!-- createTime -->
      <template #createTime="scope">
        <el-button type="primary" link @click="ElMessage.success('我是通过作用域插槽渲染的内容')">
          {{ scope.row.createTime }}
        </el-button>
      </template>
      表格操作
      <template #operation="scope">
        <el-button type="primary" link :icon="EditPen" @click="EditGroup([scope.row])">流程图跟踪</el-button>
        <!-- <el-button type="primary" link :icon="EditPen" @click="EditGroup([scope.row])">编辑</el-button>
        <el-button type="primary" link :icon="Delete" @click="deleteAccount(scope.row)">删除</el-button> -->
      </template>
    </ProTable>
  </div>
</template>

<script setup lang="tsx" name="useProTable">
import { ref, reactive } from "vue";
import { useRouter, useRoute } from "vue-router";
import { User, RoleManager, dataDictionary } from "@/api/interface";
import { useHandleData } from "@/hooks/useHandleData";
import { useDownload } from "@/hooks/useDownload";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import { ElMessage, ElMessageBox } from "element-plus";
import ProTable from "@/components/ProTable/index.vue";
import ImportExcel from "@/views/accessControl/roleManagement/components/ImportExcel/index.vue";
import UserDrawer from "@/views/dataDictionary/groupManagement/components/groupDrawer.vue";
import { ProTableInstance, ColumnProps, HeaderRenderScope } from "@/components/ProTable/interface";
import TreeFilter2 from "@/views/accessControl/roleManagement/components/authSetting/openSetting.vue";
import { CirclePlus, Delete, EditPen, Download, Upload, View, Refresh, Avatar } from "@element-plus/icons-vue";
import {
  getUserList,
  deleteUser,
  editUser,
  addUser,
  changeUserStatus,
  resetUserPassWord,
  exportUserInfo,
  BatchAddUser
} from "@/api/modules/user";
import { findNoticeRulePager, delNoticeRules } from "@/api/modules/systemTools";
import { findPageHistoryProcessInstance } from "@/api/modules/workflow";

import { roleFind, deleteRole, tempRole, importRoleData, exportRole, setResourceByRoleIds } from "@/api/modules/accessController";
import { dataDictionaryGroupFind, deleteGroup, exportDataDictionaryGroup } from "@/api/modules/dataDictionary";
const route = useRoute();
const router = useRouter();

// ProTable 实例
const proTable = ref<ProTableInstance>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable (之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({});

// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total && pageNum && pageSize 这些字段，可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行

const dataCallback = (data: any) => {
  if (data.data != null) {
    data.data.forEach((child: resList) => {
      let str = "";
      let a = child.duration;

      // const hours = parseInt((a / 1000 / 60 / 60) % 24); // 转换为小时
      //     const minutes = parseInt((a / 1000 / 60) % 60); // 转换为分钟
      //     const seconds = parseInt((a / 1000) % 60); // 转换为秒钟

      const hours = (a / 1000 / 60 / 60) % 24; // 转换为小时
      const minutes = (a / 1000 / 60) % 60; // 转换为分钟
      const seconds = (a / 1000) % 60; // 转换为秒钟
      const formattedTime = hours + "小时" + ("0" + minutes).slice(-2) + "分钟" + ("0" + seconds).slice(-2) + "秒";

      child["durationLabel"] = formattedTime;
    });
  }
  return {
    list: data.data,
    total: data.totalSize,
    pageNum: data.page,
    pageSize: data.rows
  };
};

const settingAuthRoleIds = ref("");
//子组件弹窗回调方法
const sendDataAddFrom = (data: any) => {
  setResourceByRoleIds(data + "-" + settingAuthRoleIds.value).then(res => {
    if (res.toString() == "true") {
      ElMessage.success("权限设置成功");
      proTable.value?.clearSelection();
      proTable.value?.getTableList();
    } else {
      ElMessage.error("权限设置失败");
      proTable.value?.clearSelection();
      proTable.value?.getTableList();
    }
  });
};
// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  newParams.page = newParams.pageNum;
  newParams.rows = newParams.pageSize;
  newParams._search = false;
  newParams.sidx = "processInstanceId";
  newParams.sord = "desc";

  delete newParams.pageNum;
  delete newParams.pageSize;
  return findPageHistoryProcessInstance(newParams, "noticeRuleDTO", ["_search", "sidx", "sord", "page", "rows"]);
};

// 页面按钮权限（按钮权限既可以使用 hooks，也可以直接使用 v-auth 指令，指令适合直接绑定在按钮上，hooks 适合根据按钮权限显示不同的内容）
const { BUTTONS } = useAuthButtons();

// 自定义渲染表头（使用tsx语法）
const headerRender = (scope: HeaderRenderScope<User.ResUserList>) => {
  return (
    <el-button type="primary" onClick={() => ElMessage.success("我是通过 tsx 语法渲染的表头")}>
      {scope.column.label}
    </el-button>
  );
};
export interface resList {
  companyName: string;
  companyNo: string;
  dataFlag: string;
  emailAddress: string;

  emailTemp: string;
  emailTitleTemp: string;
  imNotice: boolean;
  imTemp: string;
  lastUpdater: string;
  mailNotice: boolean;
  module: string;
  noticeRuleId: number;
  noticeRuleName: string;
  noticeRuleNo: string;
  noticeRuleType: string;
  noticeWay: string;
  pushNotice: boolean;
  pushTemp: string;
  smsNotice: boolean;
  smsTemp: string;
  technician: string;
  technicianOrEmail: string;
  url: string;
  useStatus: boolean;
  noticeType: string;
  duration: any;
}
// 表格配置项
const columns = reactive<ColumnProps<resList>[]>([
  { type: "selection", fixed: "left", width: 70 },
  { prop: "processDefinitionId", label: "流程ID", sortable: true, width: 180 },
  { prop: "processInstanceId", label: "实例ID", sortable: true, width: 180 },
  { prop: "state", label: "状态", sortable: true, width: 80 },
  { prop: "startTime", label: "开始时间", sortable: true, width: 180 },
  { prop: "endTime", label: "结束时间", sortable: true, width: 180 },
  { prop: "durationLabel", label: "持续时间", sortable: true, width: 180 },
  { prop: "endActivityName", label: "最终活动", sortable: true, width: 180 },

  { prop: "operation", label: "操作项", fixed: "right", width: 160 }
]);
const addTemplate = () => {
  router.push(`/system/tools/addNotificationTemplate?pageNo=${Math.random().toFixed(3)}`);
};
// 表格拖拽排序
const sortTable = ({ newIndex, oldIndex }: { newIndex?: number; oldIndex?: number }) => {
  console.log(newIndex, oldIndex);
  console.log(proTable.value?.tableData);
  ElMessage.success("修改列表排序成功");
};

// 删除
const deleteAccount = async (params: resList) => {
  batchDelete([params]);
  proTable.value?.clearSelection();
  proTable.value?.getTableList();
};

// 批量删除
const batchDelete = async (id: any[]) => {
  let NameStr = "";
  let idsStr = "";
  for (let i = 0; i < id.length; i++) {
    if (idsStr == "") {
      idsStr = "?ids=" + id[i].noticeRuleId;
    } else {
      idsStr = idsStr + "&ids=" + id[i].noticeRuleId;
    }
    NameStr = NameStr + id[i].noticeRuleName + ",";
  }
  ElMessageBox.confirm("是否删除选中的数据：" + NameStr + " ？", "删除确认", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
    center: true
  })
    .then(() => {
      //await useHandleData(deleteUser, { id }, "删除所选用户信息");
      delNoticeRules(idsStr).then(res => {
        ElMessage({
          type: "success",
          message: "删除成功"
        });
        proTable.value?.clearSelection();
        proTable.value?.getTableList();
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除"
      });
    });
};

const EditGroup = async (id: any[]) => {
  if (id.length == 0) {
    ElMessage.error("至少选择一条数据");
    return;
  } else if (id.length == 1) {
    router.push(`/workflow/processInstance/processInstanceImg?id=` + id[0].processInstanceId);
  } else {
    ElMessage.error("只能编辑一条数据");
    return;
  }
};
</script>
